package com.xia.controller;

import com.xia.entity.AuthRole;
import com.xia.entity.AuthRoleFunction;
import com.xia.service.RoleService;
import com.xia.utils.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Resource
    private RoleService roleService;

    @GetMapping({"", "/index"})
    public String index() {
        return "/role_list";
    }

    @GetMapping("/all")
    @ResponseBody
    public Result getRoles() {
        return Result.ok(this.roleService.getRoles());
    }

    @PostMapping("/addEdit")
    @ResponseBody
    public Result addEditRole(AuthRole role, Long[] functionIds) {
        List<AuthRoleFunction> roleFunctionList = new ArrayList<>();
        for (Long functionId : functionIds) {
            AuthRoleFunction roleFunction = new AuthRoleFunction();
            roleFunction.setFunctionId(functionId);
            roleFunction.setStatus(1);
            roleFunctionList.add(roleFunction);
        }
        if (role.getId() == null) {
            this.roleService.addRole(role, roleFunctionList);
        } else {
            this.roleService.editRole(role, roleFunctionList);
        }
        return Result.ok();
    }

    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public Result deleteRole(@PathVariable("id") Long id) {
        roleService.deleteRole(id);
        return Result.ok();
    }

}
